import React, { useState, useEffect, useRef } from "react";
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Space, Button, DatePicker, Modal, Row, Col, InputNumber, message, Tag } from "antd";
import { SearchOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack'
import {
    apiStockPurchaseDetailsAdd,
    apiStockPurchaseView,
    apiStockPurchaseDetailsDelet,
    apiStockPurchaseDetailsEdit
} from "@/request/procurement"
import { apiGetGoodsList, apiGetGoodsDetail } from '@/request/marketingTool'
import '../style/index.scss'
import { exportSheetTable } from "../../../../utils/exportTable";

const { Option } = Select
const addFormRef = React.createRef()
const { Search } = Input

const ProcureAdd = (props) => {
    const [Purchase, setPurchase] = useState(null)
    const [isOutsource, setIsOutsource] = useState(true)
    const [isSave, onSave] = useState(false);
    const [isModalVisible, addVisible] = useState(false);
    const [library, setLibraryName] = useState();
    const [supplier, setSupplierName] = useState();
    const [libraryId, setLibraryId] = useState(null);
    const [supplierId, setSupplierId] = useState(null);
    const [dataSource, setdataSource] = useState([]);
    const [goodsList, setGoodsList] = useState([]);
    const [productSku, setProductSku] = useState([]);
    const [currentSku, setCurrentSkuSku] = useState([]);
    const [materialId, setMaterialId] = useState([]);
    const [submit, setSubmit] = useState(true)
    const [searchDataSource, setSearchDataSource] = useState([])
    const [modalTitle, setModalTitle] = useState('添加')
    const [editID, setEditID] = useState(null)
    const [btnStatus, setBtnStatus] = useState(null)
    // const [downLoading, setDownLoading] = useState(false);
    const columns = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            render: (text, record, index) => {
                return record.code === "合计" ? '' : index + 1

            }
        },
        {
            title: "采购单号",
            dataIndex: "code",
            key: "code",
        },
        {
            title: "物品名称",
            dataIndex: "goodsName",
            key: "goodsName",
        },
        {
            title: '物料名称',
            dataIndex: 'materialName',
            key: 'materialName'
        },
        {
            title: "物料编码",
            dataIndex: "goodsSkuNo",
            key: "goodsSkuNo",
        },
        {
            title: "规格名",
            dataIndex: "goodsSkuName",
            key: "goodsSkuName",
        },
        // {
        //     title:"skuID",
        //     dataIndex:"goodsSkuId",
        //     key:"goodsSkuId",
        // },
        {
            title: "含税单价",
            dataIndex: "taxPrice",
            key: "taxPrice",
            render: (text) => {
                return text !== null ? <React.$Price price={text} /> : ""
            }
        },
        {
            title: "含税总价",
            dataIndex: "taxNumPrice",
            key: "taxNumPrice",
            render: (text) => {
                return text !== null ? <React.$Price price={text} /> : "/"
            }
        },
        {
            title: "应收数量",
            dataIndex: "shouldInNum",
            key: "shouldInNum",
        },
        {
            title: "操作",
            key: "todo",
            render: (text, render, index) => {
                // console.log(render);
                let disabled = false
                if (render.status == 3) return ''
                if (render.realInNum > 0) {
                    disabled = true
                }
                return render.code === "合计" || isOutsource ? "" : <div>
                    {btnStatus ? <TheButton haspermi={['procurement:details:edit']} onClick={() => editGoods(true, render)} disabled={disabled}>编辑</TheButton> : []}
                    <TheButton haspermi={['procurement:details:delet']} onClick={() => detailsDel(render.id, index)}
                        disabled={disabled}>删除</TheButton>
                </div>
            }
        },
    ]
    useEffect(() => {
        getData()
    }, [])
    let getData = () => {
        apiStockPurchaseView({ id: props.match.params.id }).then(
            (res) => {
                if (res.code === 0 && res.data) {
                    if (res.data.isOutsource) {
                        setIsOutsource(false)
                    }
                    if (res.data.status !== 0) {
                        onSave(true)
                    }
                    if (res.data.status == 0 || res.data.status == 1) {
                        setSubmit(true)
                    }
                    else {
                        setSubmit(false)
                    }
                    if (res.data.status == 0) {
                        //显示提交
                        setBtnStatus(true)
                    }
                    else if (res.data.status == 1) {
                        //显示撤销
                        setBtnStatus(false)
                    }
                    setPurchase(res.data)
                    setdataSource(res.data.stockPurchaseDetailsVos)
                    setSearchDataSource(res.data.stockPurchaseDetailsVos)
                    setLibraryName(res.data.libraryName)
                    setSupplierName(res.data.supplierName)
                    setLibraryId(res.data.libraryId)
                    setSupplierId(res.data.supplierId)
                    apiGetGoodsList({ libraryId: res.data.libraryId, type: 1 }).then(
                        (res) => {
                            if (res.code === 0 && res.data) {
                                setGoodsList(res.data)
                            }
                        }
                    )
                }
            }
        )
    }
    let reset = () => {
        setProductSku([])
        addFormRef.current.setFieldsValue({
            goodsId: '',
            shouldInNum: '',
            taxPrice: "",
            taxNumPrice: ""
        })
    }
    let goodsChange = (e, row) => {
        // console.log(e)
        GetGoodsDetail(e)
    }
    let triggerSkuTag = (value) => {
        setCurrentSkuSku(value)
    }
    let onFinishAdd = (value) => {
        let skuName = currentSku.skuAttribute.map(item =>
            item.value
        ).join(",")
        console.log(Purchase);
        let params = {
            purchaseNoteId: Purchase.id,
            goodsName: productSku.goodsInfo.goodsName,
            goodsSkuNo: currentSku.goodsSkuNo,
            goodsSkuName: skuName,
            goodsSkuId: currentSku.SKUId,
            shouldInNum: value.shouldInNum,
            taxPrice: (value.taxPrice * 100).toFixed(0),
            taxNumPrice: (value.taxNumPrice * 100).toFixed(0),
            code: Purchase.code,
        }
        console.log(params);
        if (modalTitle == '添加') {
            apiStockPurchaseDetailsAdd({ ...params }).then(
                (res) => {
                    if (res.code === 0 && res.data) {
                        apiStockPurchaseView({ id: props.match.params.id }).then(
                            (res) => {
                                if (res.code === 0 && res.data) {
                                    if (res.data.status !== 0) {
                                        onSave(true)
                                    }
                                    setdataSource(res.data.stockPurchaseDetailsVos)
                                    setSearchDataSource(res.data.stockPurchaseDetailsVos)
                                }
                            }
                        )
                        console.log(dataSource);
                        addGoods(false)
                    }
                }
            )
        } else {
            params.id = editID
            apiStockPurchaseDetailsEdit({ ...params }).then(
                (res) => {
                    if (res.code === 0 && res.data) {
                        apiStockPurchaseView({ id: props.match.params.id }).then(
                            (res) => {
                                if (res.code === 0 && res.data) {
                                    if (res.data.status !== 0) {
                                        onSave(true)
                                    }
                                    setdataSource(res.data.stockPurchaseDetailsVos)
                                    setSearchDataSource(res.data.stockPurchaseDetailsVos)
                                }
                            }
                        )
                        // console.log(dataSource);
                        editGoods(false)
                    }
                }
            )
        }
    }
    let detailsDel = (id, index) => {
        apiStockPurchaseDetailsDelet({ id }).then(
            (res) => {
                if (res.code === 0) {
                    message.info("删除成功")
                    apiStockPurchaseView({ id: props.match.params.id }).then(
                        (res) => {
                            if (res.code === 0 && res.data) {
                                if (res.data.status !== 0) {
                                    onSave(true)
                                }
                                setdataSource(res.data.stockPurchaseDetailsVos)
                                setSearchDataSource(res.data.stockPurchaseDetailsVos)
                            }
                        }
                    )
                }
            }
        )
    }

    let selectFilter = (input, option) => {
        const materialIds = option.option.materialIds.toLowerCase().split(',')
        const result = option.children.toLowerCase().includes(input.toLowerCase()) || materialIds.includes(input.toLowerCase())
        return result
    }
    let addGoods = (e) => {
        addVisible(e)
        setModalTitle('添加')
        if (e === false) {
            reset()
        }
    }
    let editGoods = async (e, data) => {
        await addVisible(e)
        setModalTitle('修改')

        if (data) {
            setEditID(data.id)
            apiGetGoodsDetail({ goodsId: data.goodsId, libraryId }).then(
                (res) => {
                    if (res.code === 0) {
                        setProductSku(res.data)
                        let result = res.data.skuInfo.filter(item => item.materialId === data.goodsSkuNo)
                        setCurrentSkuSku(result.length > 0 ? result[0] : res.data.skuInfo[0])
                    }
                }
            )
            addFormRef.current.setFieldsValue({
                goodsId: data.goodsId,
                shouldInNum: data.shouldInNum,
                taxPrice: data.taxPrice / 100,
                taxNumPrice: data.taxNumPrice / 100
            })
        }
        if (e === false) {
            reset()
        }
    }
    let exportGoods = (e) => {
        // setDownLoading(true)
        let tH_data = [
            {
                title: `${library}-采购单详情(供应商:${supplier})`,
                prop: '',
                children: [
                    { prop: 'index', title: '序号' },
                    { prop: 'code', title: '采购单号' },
                    { prop: 'goodsName', title: '商品名称' },
                    { prop: 'materialName', title: '物料名称' },
                    { prop: 'goodsSkuNo', title: '物料编码' },
                    { prop: 'goodsSkuName', title: '规格名' },
                    { prop: 'taxPrice', title: '含税单价', valueType: 'number' },
                    { prop: 'taxNumPrice', title: '含税总价', valueType: 'number' },
                    { prop: 'shouldInNum', title: '应收数量', valueType: 'number' },
                ]
            }
        ]
        let code = dataSource[0].code;
        let tB_data = dataSource.map((item, index) => {
            return {
                index: index + 1,
                code: item.code,
                goodsName: item.goodsName,
                materialName: item.materialName,
                goodsSkuNo: item.goodsSkuNo,
                goodsSkuName: item.goodsSkuName,
                taxPrice: item.taxPrice / 100,
                taxNumPrice: item.taxNumPrice / 100,
                shouldInNum: item.shouldInNum,
            }
        })
        exportSheetTable({
            fileName: `${library}-采购单详情-${code}`, tH_data: tH_data, tB_data: tB_data, isSheet: true, merge: false
        })
    }
    let execute = (e) => {
        React.$confirm({
            title: "提示",  
            
            type: 'warning',
            content: "是否确定操作？",
            onOk: async () => {
                let res = await React.$post("/admin/stockPurchaseNote/edit", {
                    id: props.match.params.id,
                    status: e
                })
                if (res.code === 0) {
                    onSave(e ? true : false)
                    if(Purchase.isOutsource==0){
                        window.location.reload()
                        return false
                    }
                    // setSubmit(false)
                    setBtnStatus(e ? false : true)
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                }
            }
        })

    }
    let GetGoodsDetail = (goodsId, skuId) => {
        apiGetGoodsDetail({ goodsId, libraryId }).then(
            (res) => {
                if (res.code === 0) {
                    console.log(materialId)
                    if (materialId) {
                        setProductSku(res.data)
                        let result = res.data.skuInfo.filter(item => item.materialId === materialId)
                        setCurrentSkuSku(result.length > 0 ? result[0] : res.data.skuInfo[0])
                    } else {
                        setProductSku(res.data)
                        setCurrentSkuSku(res.data.skuInfo[0])
                    }
                }
            }
        )
    }
    const onBlur = (materialId) => {
        // console.log('materialId',materialId)
        setMaterialId(materialId)
    }
    let setSearchValue = (value) => {
        // console.log(value);
        let search = value.target.value.trim()
        if (search) {
            getSearchData(dataSource, search)
        } else {
            setSearchDataSource(dataSource)
        }
    }
    let getSearchData = (aim, searchVal) => {
        // console.log(aim, searchVal);
        let newArr = []
        for (var i = 0; i < aim.length - 1; i++) {
            let value = aim[i].goodsSkuNo
            console.log(value);
            if (value.includes(searchVal)) {
                newArr.push(aim[i]);//将值放入第二个数组
            }
        }
        setSearchDataSource(newArr)
    }
    const onValuesChange = (obj, values) => {
        let { shouldInNum, taxPrice, taxNumPrice } = values
        Object.keys(obj).forEach(item => {
            if (item == 'shouldInNum' || item == 'taxPrice') {
                try {
                    taxNumPrice = shouldInNum * taxPrice
                    addFormRef.current.setFieldsValue({
                        taxNumPrice
                    })
                } catch (error) {
                    console.warn('计算异常');
                }
            }
        })

        // taxNumPrice 总价
        // taxPrice 单价
        // shouldInNum 入库数
    }
    return (
        <div className="p-layout-box">
            <GoBack history={props.history} title="采购单详情" />
            <Form
                labelCol={{
                    span: 6,
                }}
                wrapperCol={{
                    span: 18,
                }}

                style={{ marginBottom: 12, marginTop: 12 }}>

                <Row>
                    <Search
                        placeholder="请输入物料编码"
                        onChange={(e) => setSearchValue(e)}
                        style={{
                            width: 200,
                        }}
                        allowClear
                    />
                    {/* <Col span={8}>
                        <Form.Item name={"storeServiceName"} label="采购日期" >
                            <Input placeholder={"出库时间"}  />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name={"storeServiceName1"} label="采购类型" >
                            <Input placeholder={"出库类型"} />
                        </Form.Item>
                    </Col> */}
                    <Col span={8}>
                        <Form.Item name={"libraryId"} label="采购仓库"
                            rules={[{ required: true }]}>
                            <div>
                                {library}
                            </div>

                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name={"supplierId"} label="供应商"
                            rules={[{ required: true }]}>
                            {supplier}
                        </Form.Item>
                    </Col>
                    {/* <Col span={8}>
                        <Form.Item name={"storeServiceName4"} label="登记人">
                            <Input placeholder={"领取人"} />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name={"storeServiceName5"} label="验收人">
                            <Input placeholder={"领取部门"} />
                        </Form.Item>
                    </Col> */}
                </Row>
            </Form>
            <Space style={{ marginBottom: 12 }}>
                {Purchase && Purchase.status == 3 ? null :
                    !isSave ?
                        <TheButton onClick={() => addGoods(true)} haspermi={['procurement:goods:add']} size="middle"
                            type="primary">添加商品</TheButton> : null
                }
                {
                    <TheButton onClick={() => exportGoods(true)} haspermi={['procurement:warehouse:export']}
                        type="dashed" size="middle">导出</TheButton>
                }
            </Space>
            <TheTable
                scroll={{ x: "max-content", y: '63vh' }}
                columns={columns}
                dataSource={searchDataSource}
            />
            {/* <ThePagination
                pageNo={1}
                pageSize={10}
                total={0}
            // pageChange={this.pageChange}
            /> */}
            <div style={{ textAlign: 'center', marginTop: 12 }}>
                {
                    Purchase && Purchase.status == 3 ? null :
                        (submit ? (btnStatus ?
                            <TheButton type="primary" haspermi={['procurement:list:backout']} size='middle'
                                onClick={() => execute(1)}>提交</TheButton> : (Purchase&&Purchase.isOutsource == 0 && Purchase.portionDelivery == 1 ? null :
                                    <TheButton type="default" haspermi={['procurement:list:execute']} size='middle'
                                        onClick={() => execute(0)}>撤销</TheButton>)) : [])
                }
            </div>

            <Modal title={modalTitle + "采购商品"} visible={isModalVisible} width="40%"
                onCancel={() => addGoods(false)}
                footer={null}
            >
                <Form
                    labelCol={{
                        span: 4,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    ref={addFormRef}
                    onFinish={(values) => onFinishAdd(values)}
                    dataSource={dataSource}
                    onValuesChange={onValuesChange}

                >
                    <Row>

                        <Col span={24}>
                            <Form.Item

                                label="选择商品"
                                name="goodsId"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择商品!',
                                    },
                                ]}
                            >
                                <Select
                                
                                    showSearch
                                    optionFilterProp="children"
                                    filterOption={(input, option) => selectFilter(input, option)}
                                    style={{
                                        width: '100%',
                                    }}
                                    onSearch={(e) => onBlur(e)}
                                    onSelect={(e, obj) => goodsChange(e, obj)}
                                    placeholder="请选择商品"
                                >
                                    {

                                        goodsList.map(item => <Option option={item} key={item.goodsId}
                                            value={item.goodsId}>{item.goodsName}</Option>)
                                    }
                                </Select>

                            </Form.Item>
                        </Col>

                        <Col>
                            {
                                productSku.hasOwnProperty('goodsInfo') ?
                                    <Form.Item
                                        wrapperCol={{
                                            offset: 4,
                                            span: 16,
                                        }}
                                    >
                                        <div className='goodsDesc'>
                                            <div className='info'>
                                                <img
                                                    src={currentSku.imageFile ? currentSku.imageFile.split(',')[0] : ''}
                                                    alt="商品图片" className='goodsImg' />
                                                <div className="goodsInfo">
                                                    <div className='name'>{productSku.goodsInfo.goodsName}</div>
                                                    <div className="stock">
                                                        物料名称：{currentSku.materialName}
                                                    </div>
                                                    <div className='stock'>
                                                        物料ID：{currentSku.materialId}
                                                    </div>
                                                    <div className='stock'>
                                                        可售库存：{currentSku.stock}
                                                    </div>
                                                    <div className='stock'>
                                                        待出库存：{currentSku.waiteOutCount}
                                                    </div>
                                                    <div className='stock'>
                                                        实际库存：{currentSku.realStock}
                                                    </div>
                                                </div>
                                            </div>
                                            <div className='goodsSku'>
                                                {
                                                    productSku.skuInfo.map(item =>
                                                        <Tag className='tag' key={item.SKUId}
                                                            color={item.SKUId === currentSku.SKUId ? "cyan" : ''}
                                                            onClick={() => triggerSkuTag(item)}>
                                                            {item.skuAttribute.map(item2 => item2.value).join(',')}
                                                        </Tag>
                                                    )
                                                }

                                            </div>
                                        </div>
                                    </Form.Item> : null
                            }
                        </Col>

                        {/* <Col span={24}>
                        <Form.Item
                            label="入库类型"
                            name="dataType"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入!',
                                },
                            ]}
                        >
                            <Select>
                                {
                                    options.map(item => {
                                        return <Option value={item.value}>{item.label}</Option>
                                    })
                                }

                            </Select>
                        </Form.Item>
                    </Col> */}
                      <Col span={24}>
                            <Form.Item
                                label="入库数"
                                name="shouldInNum"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入!',
                                    },
                                ]}
                            >
                                <InputNumber style={{}} precision={0} min={0} />
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                label="含税单价"
                                name="taxPrice"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入!',
                                    },
                                ]}
                            >
                                <InputNumber style={{}} precision={2} min={0} />
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                label="含税总价"
                                name="taxNumPrice"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入!',
                                    },
                                ]}
                            >
                                <InputNumber style={{}} precision={2} min={0} />
                            </Form.Item>
                        </Col>
                      
                        <Col>
                            <Form.Item wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}>
                                <Space size="small" style={{ marginLeft: 10 }}>

                                    <Button type="default" onClick={() => reset()}>
                                        重置
                                    </Button>
                                    <Button type="primary" htmlType="submit">
                                        确定
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </div>
    );
}

export default ProcureAdd
